package com.ma.schoolproject.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ma.schoolproject.config.SaTokenProperties;
import com.ma.schoolproject.config.Valida;
import com.ma.schoolproject.entitys.LoginUser;
import com.ma.schoolproject.entitys.User;
import com.ma.schoolproject.mapper.UserMapper;
import com.ma.schoolproject.service.UserService;
import com.ma.schoolproject.utils.PhoneValidator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


@RestController
@RequestMapping( "/user")
@RequiredArgsConstructor
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private SaTokenProperties saTokenProperties;

    @PostMapping("/login")
    //登录接口
    public SaResult login(LoginUser loginUser) {
        //参数校验
        if (loginUser == null){
            return SaResult.error("参数为空");
        }
        // 去除用户名和密码的空格
        String phone = loginUser.getPhone();
        String password = loginUser.getPassword();

        if (StringUtils.hasText(phone)) {
            phone = phone.trim();
        }

        if (StringUtils.hasText(password)) {
            password = password.trim();
        }

        // 校验手机号码
        if (!StringUtils.hasText(phone)) {
            return SaResult.error("手机号码不能为空");
        }

        PhoneValidator.PhoneValidationResult phoneResult = PhoneValidator.validate(phone);
        if (!phoneResult.isValid()) {
            return SaResult.error(phoneResult.getMessage());
        }

        // 校验密码
        if (!StringUtils.hasText(password)) {
            return SaResult.error("密码不能为空");
        }

        // 更新loginUser的值
        loginUser.setPhone(phone);
        loginUser.setPassword(password);
        //查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();
        queryWrapper.eq(User::getPhone,loginUser.getPhone());
        User user = userMapper.selectOne(queryWrapper);
        if(user==null) return SaResult.error("没有此用户");
        if(user.getStatus()!=0){
            return SaResult.error("账户处于异常状态");
        }
        String s = SaSecureUtil.aesDecrypt(saTokenProperties.getVerifyKey(),user.getPassword());
        if(s.equals(loginUser.getPassword())) {
            //登录成功
            StpUtil.login(loginUser.getPhone());
            return  SaResult.data(StpUtil.getTokenInfo());
        }else {
            return SaResult.error("密码错误");
        }
    }

    /**
     * 退出接口     发现一个问题，就是请求这个接口必须要携带token，如果没有携带token会导致redis中的数据还存在
     * @return
     */
    @GetMapping("/logout")
    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok("退出成功");
    }

    @GetMapping("/id")
    public SaResult selectUser(String id) {
        return userService.selectUser(id);
    }

    @PutMapping("/update")
    public SaResult updateUser(@RequestBody User user) {
        return userService.updateUser(user);
    }

    @PostMapping("/save")
    public SaResult saveUser(@Validated(Valida.Create.class) @RequestBody User user) {
        return userService.saveUser(user);
    }

    @GetMapping("pageUser")
    public SaResult pageUser(@RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer size
            ,@RequestParam Map<String,Object> searchMap) {
        return userService.pageUser(page,size,searchMap);
    }
}
